package top.java.multithreading;

/**
 *              线程与通信例题      生产者与消费者问题
 */

public class ThreadTest10 {
    public static void main(String[] args) {

        Clerk clerk = new Clerk();
        Productor productor = new Productor(clerk);
        Customerr customerr = new Customerr(clerk);
        Thread p1 = new Thread(productor);
        Thread p2 = new Thread(productor);
        Thread p3 = new Thread(productor);
        Thread c1 = new Thread(customerr);
        Thread c2 = new Thread(customerr);
        p1.setName("生产者1");
        p2.setName("生产者2");
        p3.setName("生产者3");
        c1.setName("消费者1");
        c2.setName("消费者2");
        p1.start();
        p2.start();
        p3.start();
        c1.start();
        c2.start();
    }
}

class Clerk {

    private int product = 0;

    //消费产品
    public synchronized void customerrProduct() {
        if (product > 0) {
            System.out.println(Thread.currentThread().getName() + "：消费了第" + product + "个产品");
            product--;
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //生产产品
    public synchronized void productorProduct() {
        if (product < 20) {
            product++;
            notify();
            System.out.println(Thread.currentThread().getName() + "：生产了第" + product + "个产品");
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


class Productor implements Runnable {

    private Clerk clerk;

    public Productor(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "开始生产");
        while (true) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.productorProduct();
        }
    }
}

class Customerr implements Runnable {

    private Clerk clerk;

    public Customerr(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "开始消费");
        while (true) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.customerrProduct();
        }
    }
}
